package chapter07

/**
 * Created with IntelliJ IDEA.
 * ClassName: Test14_Hight
 * Package: chapter07
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 *          Date: 2023-06-28
 *          Time: 21:11
 */

//集合高级函数
object Test14_High {
  def main(args: Array[String]): Unit = {

    //主要是集合的转换 得到的还是集合类型
    val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

    //过滤
    //选取偶数
    val evenList = list.filter((elem: Int) => {
      elem % 2 == 0
    })
    println(evenList)
    //下划线 是连着参数和 => 符号一起省略
    println(list.filter(_ % 2 == 0))
    println(list.filter(_ % 2 == 1))

    println("-----------------")
    //map 映射
    //把集合每个数乘2
    println(list.map(_ * 2))
    //平方 两个参数
    println(list.map(x => x * x))

    println("------------------------")
    //扁平化
    val nes = List(List(1, 2, 3), List(4, 5), List(6, 7))

    val flatList = nes(0) ::: nes(1) ::: nes(2)
    //把里面的List完全 大散放到新的list里面
    println(flatList) //List(1, 2, 3, 4, 5, 6, 7)
    //更简单的操作 直接打散在结合成一个
    val nes2 = nes.flatten
    println(nes2)

    println("----------------------------")
    //扁平化在映射
    //将一组字符串分词 并保存成单词列表
    val strings: List[String] = List("hello world", "hello Scala", "hello Java", "we study")
    //1.等到每个单词 map有两个
    val splitList: List[Array[String]] = strings.map(string => string.split(" ")) //分词
    println(splitList)
    val fla = splitList.flatten
    println(fla) //List(hello, world, hello, Scala, hello, Java, we, study)

    //合并以上两个操作的函数
    val fml = strings.flatMap(_.split(" "))
    println(fml)

    println("-------------------------")

    val intToInts: Map[Int, List[Int]] = list.groupBy(_ % 2)
    //分组操作 得到map
    //分奇偶数两组
    val groupMap = intToInts
    println(groupMap)
    val stringToInts: Map[String, List[Int]] = list.groupBy(data => {
      if (data % 2 == 0) "偶数" else "奇数"
    })
    val groupMap2 = stringToInts

    println(groupMap2)

    //给定一组词汇按照单词首字母分组
    val wordList = List("china","ama","bob","tony","canad","japen")
    println(wordList.groupBy(_.charAt(0)))

  }

}
